package com.proxy.server.frontend.adapter;

import com.proxy.common.packet.BinaryPacket;
import com.proxy.server.frontend.dispatcher.Dispatcher;
import com.proxy.server.frontend.session.ProxySession;
import com.proxy.server.context.AppContext;
import com.proxy.server.frontend.FrontendConnection;
import com.proxy.server.frontend.handler.AuthHandler;
import com.proxy.server.frontend.session.Session;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Created by liufish on 16/7/15.
 */
public class FrontendCoreAdapter  extends ChannelInboundHandlerAdapter{


    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        FrontendConnection connection = new FrontendConnection(ctx.channel());
        Session session = new ProxySession(connection);
        AppContext.getInstance().registeredSession(ctx.channel(),session);
        AuthHandler.handshake(connection);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        AppContext.getInstance().unRegisteredDession(ctx.channel());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        BinaryPacket bin = (BinaryPacket) msg;

        Session session = AppContext.getInstance().getProxySession(ctx.channel());
        if (session == null) {
            FrontendConnection connection = new FrontendConnection(ctx.channel());
            session = new ProxySession(connection);
            AppContext.getInstance().registeredSession(ctx.channel(),session);
        }
        //未认证
        if (!session.getFrontendConnection().isAuth()) {
            //认证过程
            AuthHandler.auth(bin,session.getFrontendConnection());
            return;
        }
        Dispatcher.dispatch(bin, session);

    }

    
}
